<script setup lang="ts">
import topTable from './components/top-table.vue';
import loadingMask from '../loading-mask/index.vue';
import { message } from '@/components/q-message/message';
import { searchConfig } from './config/search-config';
import { tableConfig } from './config/table-config';
import { generateNameToLevel } from '@/config/constant';
import { initTopTableData } from '@/views/Base/WorkCalendar/common';
import { useUpdate } from '../../hooks/useUpdate';
import addDataStore from '@/store/modules/addDataStore';
import useEmit from '@/hooks/useEmitter';
import usePageSave from '@/hooks/usePageSave';
import { difference } from 'lodash-es';
import { doGetEquipmentList, doAddClassSystem } from '@/api/base/workCalendar/shiftSystem/index.ts';
import type {
    WorkingDayPeriods,
    EquipmentCollection,
    UpdateClassSystemData
} from '@/api/base/workCalendar/shiftSystem/model/type';

defineOptions({
    name: 'ShiftSystemAdd'
});

const STORE_KEY = 'classSystemAddData'; // store数据的key
const { startRecording, isUpdate } = useEmit(STORE_KEY); // 页面标签路由关闭二次确认事件监听 EventBus

const store = addDataStore();

// 新增时表格数组长度为0 需要排除掉监听
const excludeKey = ref(['equipmentIds']);

// top-table 表格数据
const topTableData = ref<WorkingDayPeriods[]>(initTopTableData());

// 下方表格选中的id
const equipmentIds = ref<number[]>([]);

// 表格ref
const topTableRef = ref<InstanceType<typeof topTable>>();

// 工作时段勾选的id
const workingDays = computed(() => topTableRef.value?.workingDays);

const { getMaxHeight, modalSlotRef, modalOk, loading } = useModal({
    data: { topTableData, equipmentIds, workingDays },
    excludeKey
});

// 重新排班的hooks

const { loadingShow, classSystemUpdate } = useUpdate(() => {
    usePageSave('/workCalendar/shiftSystem');
});

/**
 * @: 打开弹框
 */
const route = useRoute();
const init = () => {
    equipmentIds.value = [];
    preIds.value = [];
    delIds.value = [];
    topTableData.value = initTopTableData();

    startRecording(route.name as string, { topTableData, equipmentIds, workingDays });
    isError.value = false;
};

/**
 * @: 更新top-table数据
 */
const updateTopTableData = (periodDesc: string, id: number, rowWorkingDay: number[]) => {
    topTableData.value = topTableData.value.map(item => {
        if (rowWorkingDay.includes(item.workingDay)) {
            return {
                ...item,
                periodId: id,
                periodDesc
            };
        }
        return item;
    });
};

/**
 * @: 选中相关
 */
const preIds = ref<number[]>([]);
const delIds = ref<number[]>([]);
const selection = (row: EquipmentCollection[]) => {
    isError.value = false;
    const ids = row.map(item => item.id);
    if (preIds.value.length) {
        // 对比id筛选出取消的id
        const arr = difference(preIds.value, ids);
        if (arr) {
            delIds.value.push(...arr);
        }
    }
    equipmentIds.value = ids;
    preIds.value = ids;
};

/**
 * @: 提交
 */
const isError = ref(false);
const handleSubmit = async () => {
    if (equipmentIds.value.length === 0) {
        isError.value = true;
        message.error(`请至少选择一个工作设备！`);
        return;
    }

    const checkData = topTableRef.value?.workingDays;
    let valid = false;
    // 把没有选中的过滤掉不传递给后端
    const paramsData = topTableData.value.map(item => {
        if (checkData?.includes(item.workingDay)) {
            if (item.periodDesc === '' && !valid) {
                valid = true;
            }
            return item;
        }
        return {
            workingDay: item.workingDay,
            periodId: 0,
            periodDesc: ''
        };
    });

    if (valid) {
        message.error(`选中后必须选择工作时段！`);
        return;
    }
    //至少选择一个工作时段 ， 全部为零说明没有选择工作时段
    const empty = paramsData.every(item => item.periodId === 0);
    if (empty) {
        message.error(`请至少选择一个工作时段！`);
        return;
    }

    const updateData: UpdateClassSystemData = {
        workingDayPeriods: paramsData,
        equipmentIds: equipmentIds.value
    };
    try {
        const res = await doAddClassSystem(updateData);
        classSystemUpdate();
        return res;
    } catch (error) {
        console.log('error');
    }
};

watch(
    () => modalSlotRef.value?.tableData,
    (newData: EquipmentCollection[]) => {
        newData?.forEach(item => {
            if (item.selected) {
                modalSlotRef.value.toggleRowSelection(item, true);
            }
        });
    }
);

// 工作设备列表禁用
const disabledFn = (row: EquipmentCollection) => !row.bound;

onActivated(() => {
    isUpdate(init);
});

onUnmounted(() => {
    store.handleAddData(STORE_KEY);
});
</script>

<template>
    <q-page>
        <top-table
            ref="topTableRef"
            :tableData="topTableData"
            :isEdit="false"
            :isCheck="false"
            @update="updateTopTableData"
        >
            <!-- 保存按钮 -->
            <q-submit-button
                size="default"
                :hide-label="true"
                align="right"
                :horizontal="true"
                :loading="loading"
                :cancel-button="false"
                @save="modalOk(handleSubmit)"
            />
        </top-table>

        <!-- 工作设备 -->
        <div class="m-t-32 m-b-24">
            工作设备列表 <span class="danger">*</span>
            <Transition name="form-error">
                <span v-show="isError" class="danger m-l-16 f14">请至少选择一个工作设备！</span>
            </Transition>
        </div>

        <!-- 搜索 -->
        <base-search
            :table-ref="modalSlotRef"
            :search-config="searchConfig"
            :close-min-width="true"
        >
            <q-push-button :is-text="false" @click="$router.push('/equipment')" />
        </base-search>

        <base-table
            :id="generateNameToLevel('1')"
            ref="modalSlotRef"
            :get-data-fn="doGetEquipmentList"
            :max-height="getMaxHeight"
            :modal-mode="true"
            :show-setting="false"
            :table-config="tableConfig"
            :selectable="disabledFn"
            @selection-change="selection"
        >
        </base-table>

        <!-- loading -->
        <loading-mask :loading-show="loadingShow" />
    </q-page>
</template>

<style scoped lang="scss">
@include b(danger) {
    color: #f00;
}

.form-error-enter-from,
.form-error-leave-to {
    opacity: 0;
}

.form-error-enter-active,
.form-error-leave-active {
    transition: opacity 0.3s;
}
</style>
